﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeProjectsModel;
using System.IO;
using System.Web.Security;
using WeProjects.Filters;

namespace WeProjects.Controllers
{
    
    [Authorize]
    [InitializeSimpleMembership]
    public class DocumentController : Controller
    {
        private ProjectsDBEntities db = new ProjectsDBEntities();

        //
        // GET: /Document/

        public ActionResult Index()
        {
            try
            {
                //文档库只显示用户个人文档，不显示项目文件
                var documents = db.Documents.Include(d => d.Member).Include(d => d.Project).Where(d => d.ProjectID == null);
                return View(documents.ToList());
            }
            catch
            {
                return RedirectToAction("../Home/Index");
            }
        }
        
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="uploadFile"></param>
        /// <param name="id">taskID任务id</param>
        /// <param name="backURL"></param>
        /// <param name="isTask">是否在task页面添加，如是，关联任务</param>
        /// <returns></returns>
        public ActionResult Upload(HttpPostedFileBase uploadFile, int? id,int? project,string backURL,string isTask)
        {
            //try
            //{
                if (uploadFile != null && uploadFile.ContentLength > 0)
                {
                    string path = Server.MapPath("~/Files/user/"+Membership.GetUser().ProviderUserKey.ToString()+"/");
                    string fileName = Path.GetFileName(uploadFile.FileName);
                    int fileSize = uploadFile.ContentLength / 1024;//文件大小KB
                    string newpath = Path.Combine(path, fileName);
                    //string newurl = "/Files/" + id.ToString() + "/" + fileName;
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    uploadFile.SaveAs(newpath);
                    var doc = new Document();
                    doc.Name = fileName;
                    doc.Size = fileSize;
                    doc.ProjectID = project;
                    doc.UploadDateTime = DateTime.Now;

                    doc.UploaderID = int.Parse(Membership.GetUser().ProviderUserKey.ToString());
                    //doc.UploaderID = int.Parse(Session["userid"].ToString());//用户id      
                    db.Documents.Add(doc);
                    db.SaveChanges();
                    if (isTask == "1")//如果在task页面添加，则将该id与documentID关联
                    {
                        int newID = db.Documents.Max(docid => docid.ID);
                        db.Database.ExecuteSqlCommand("insert into TaskDocuments(TaskID,DocumentID) values('" + id + "','" + newID + "')");
                    }
                }
                //return RedirectToAction(backURL + id);
                return RedirectToAction("Details", "Task", new { id = id, projectID = project });
            //}
            //catch (Exception e)
            //{
            //    return RedirectToAction("/Index/");
            //}
        }
        /// <summary>
        ///下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DownloadFile(int file,int uploader)
        {
            Document document = db.Documents.Find(file);
            if (document == null)
            {
                return HttpNotFound();
            }
            string fileName = document.Name;
            string path = Server.MapPath("~/Files/user/"+uploader+"/" + fileName);          
            
            string downName = Path.GetFileName(path);
            return File(path, "1", downName);
        }
        public FileResult Download(int id) //Document ID.
        {
            var doc = db.Documents.Find(id);
            if (doc == null)
            {
                //return HttpNotFound();
            }
            var path = Path.Combine(Server.MapPath("~/Files/user/"),doc.UploaderID.ToString());
            string fullName = Path.Combine(path, doc.Name);
            if (Directory.Exists(path) && System.IO.File.Exists(fullName))
            {
                byte[] fileBytes = Helps.Utility.GetFile(fullName);
                return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, doc.Name);
            }
            else
            {
                return null;// HttpNotFound("File requested doesn't exist. Contact administrator please.");
            }
        }
        //
        // GET: /Document/Delete/5

        public ActionResult Delete(int id = 0)
        {
            try
            {
                Document document = db.Documents.Find(id);
                if (document == null)
                {
                    return HttpNotFound();
                }
                int task = document.Tasks.Count;

                //如果已经被使用，则无法删除
                if (task > 0)
                {
                    ViewBag.delCode = 0;
                    ViewBag.delMsg = "该文件已经在如下任务重使用，无法删除！";
                }
                else
                {
                    ViewBag.delCode = 1;
                    ViewBag.delMsg = "确认删除，将同时删除对应的文件？";
                }
                return View(document);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //
        // POST: /Document/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Document document = db.Documents.Find(id);
            //获取文件名
            string fileName = document.Name;

            string path = Server.MapPath("~/Files/");
            string newpath = Path.Combine(path, fileName);
            //如果存在则删除
            if(System.IO.File.Exists(newpath))
            {
                System.IO.File.Delete(newpath);
            }
            db.Documents.Remove(document);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}